package yt.kpool.activity.personal;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;
import yt.kpool.activity.setting.CreateOnlyReadActivity;
import yt.kpool.activity.setting.OnlyReadActivity;
import yt.kpool.adapter.FastLookListAdapter;
import yt.kpool.base.BaseApplication;
import yt.kpool.bean.ChildAccountAPIKeyBean;
import yt.kpool.bean.FastLookAccountBean;
import yt.kpool.bean.KeyLoginBean;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.NetWorkUtil;
import yt.kpool.util.SPUtil;
import yt.kpool.util.TitleControl;
import yt.kpool.util.ToastUtil;
import yt.kpool.view.dialog.LoadingDialog;

/**
 * 快速查看
 */
public class FastLookActivity extends AppCompatActivity {
    @BindView(R.id.edit_content)
    EditText edit_content;
    @BindView(R.id.listview)
    ListView listview;

    private List<FastLookAccountBean> fastLookAccountBeans;
    private FastLookListAdapter fastLookListAdapter;
    private SQLiteDatabase db;
    private LoadingDialog loadingDialog;
    private String linkss = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fast_look);
        ButterKnife.bind(this);
        initTitle();
        initDb();
    }


    @OnClick({R.id.iv_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_search://快速查看
                linkss = edit_content.getText().toString().trim();
                if ("".equals(edit_content.getText().toString().trim())) {
                    ToastUtil.showToast(this, "请输入链接");
                    break;
                } else {
                    int i = edit_content.getText().toString().trim().indexOf("=");
                    if (i == -1) {
                        fastLogin(edit_content.getText().toString().trim());
                    } else {
                        if (edit_content.getText().toString().trim().length() > i + 1)
                            fastLogin(edit_content.getText().toString().trim().substring(i + 1));
                    }

                }

                break;

        }
    }

    /**
     * 快速登录
     *
     * @param key
     */
    private void fastLogin(String key) {
        if (NetWorkUtil.check(this)) {


            loadingDialog.show();
            NetHelperNew.KeyLogin(key, new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    loadingDialog.dismiss();
                    Log.i("-->", "快速查看返回结果：" + data);
                    KeyLoginBean keyLoginBean = MyGson.getInstance().fromJson(data, KeyLoginBean.class);
                    if (keyLoginBean.getType() == 1) {

                        List<FastLookAccountBean> fastLookAccountBeans = DataSupport.where("name=?", keyLoginBean.getData().getChildAccount().getChildAccountName()).find(FastLookAccountBean.class);
                        if (fastLookAccountBeans.size() == 0) {
                            insertDb(linkss, keyLoginBean.getData().getChildAccount().getChildAccountName(), keyLoginBean.getData().getChildAccount().getChildAccountRemark());

                        }
                        SPUtil spUtil = new SPUtil(BaseApplication.context, BaseApplication.KEYLOGIN);

                        spUtil.putString(BaseApplication.NAME, keyLoginBean.getData().getLoginModel().getUserName());
                        spUtil.putString(BaseApplication.ID, keyLoginBean.getData().getLoginModel().getUserID() + "");
                        spUtil.putString(BaseApplication.ChildAccountId, keyLoginBean.getData().getChildAccount().getChildAccountId() + "");
                        spUtil.putString(BaseApplication.ChildAccountName, keyLoginBean.getData().getChildAccount().getChildAccountName());
                        setResult(66, getIntent());
                        finish();

                    } else {
                        ToastUtil.showToast(getApplicationContext(), keyLoginBean.getContent());
                    }
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);

                    loadingDialog.dismiss();
                    ToastUtil.showToast(getApplicationContext(), msg);
                }
            });


        }

    }

    /**
     * 添加数据
     */
    private void insertDb(String link, String name, String remark) {
        FastLookAccountBean fastLookAccountBean = new FastLookAccountBean();
        fastLookAccountBean.setAccountId(1);
        fastLookAccountBean.setLink(link);
        fastLookAccountBean.setName(name);
        fastLookAccountBean.setRemark(remark);
        fastLookAccountBean.save();
    }

    /**
     * 快速查看账户数据库
     */
    private void initDb() {
        db = Connector.getDatabase();
        fastLookAccountBeans = new ArrayList<>();

        fastLookListAdapter = new FastLookListAdapter(this, fastLookAccountBeans);
        listview.setAdapter(fastLookListAdapter);

        getdata();

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if (i != fastLookListAdapter.getSelectPos()) {


                    linkss = fastLookAccountBeans.get(i).getLink();
                    String link = fastLookAccountBeans.get(i).getLink();
                    if ("".equals(link)) {
                        ToastUtil.showToast(FastLookActivity.this, "请输入链接");

                    } else {
                        int j = link.indexOf("=");
                        if (j == -1) {
                            fastLogin(link);
                        } else {
                            if (link.length() > j + 1)
                                fastLogin(link.substring(j + 1));
                        }

                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getdata();
    }

    private void getdata() {
        fastLookAccountBeans.clear();
        fastLookListAdapter.notifyDataSetChanged();
        fastLookAccountBeans.addAll(DataSupport.select("remark", "accountId", "name", "link").order("id desc").find(FastLookAccountBean.class));
        SPUtil spUtil = new SPUtil(this, BaseApplication.KEYLOGIN);
        String name = spUtil.getString(BaseApplication.ChildAccountName, "");
        int pos = -1;
        for (int i = 0; i < fastLookAccountBeans.size(); i++) {
            if (name.equals(fastLookAccountBeans.get(i).getName())) {
                pos = i;
            }
        }
        fastLookListAdapter.setSelectPos(pos);
        fastLookListAdapter.notifyDataSetChanged();
    }

    private void initTitle() {
        TitleControl titleControl = new TitleControl(this);
        titleControl.setTitle("快速查看");
        titleControl.setRightImg(R.mipmap.saoyisao, new TitleControl.OnClickRight() {
            @Override
            public void onRight() {
                if (ContextCompat.checkSelfPermission(FastLookActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(FastLookActivity.this, new String[]{Manifest.permission.CAMERA}, 66);
                    Log.i("-->", "照像权限申请");
                } else {
                    toZxing();
                }


            }
        });
        loadingDialog = new LoadingDialog(this, 0);
    }

    /**
     * 跳转扫一扫
     */
    private void toZxing() {
        Intent intent = new Intent(FastLookActivity.this, CaptureActivity.class);
        /*ZxingConfig是配置类  可以设置是否显示底部布局，闪光灯，相册，是否播放提示音  震动等动能
         * 也可以不传这个参数
         * 不传的话  默认都为默认不震动  其他都为true
         * */

        ZxingConfig config = new ZxingConfig();
        config.setShowbottomLayout(false);//底部布局（包括闪光灯和相册）
        config.setPlayBeep(false);//是否播放提示音
        config.setShake(false);//是否震动
        config.setShowAlbum(false);//是否显示相册
        config.setShowFlashLight(false);//是否显示闪光灯
        intent.putExtra(Constant.INTENT_ZXING_CONFIG, config);
        startActivityForResult(intent, 11);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 66) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                toZxing();
            } else {

                new AlertDialog.Builder(this)
                        .setTitle("权限申请")
                        .setMessage("在设置-应用-" + getString(R.string.app_name) + "-权限中启动拍照权限，以正常使用此功能")
                        .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 扫描二维码/条码回传
        if (requestCode == 11 && resultCode == RESULT_OK) {
            if (data != null) {

                String content = data.getStringExtra(Constant.CODED_CONTENT);
                Log.i("-->", "二维码内容：" + content);
                edit_content.setText("" + content);
            }
        }


    }

}
